package com.chenfan.magic.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chenfan.magic.base.R;
import com.chenfan.magic.base.S;
import com.chenfan.magic.dao.ScriptsMapper;
import com.chenfan.magic.entity.IdcScripts;
import com.chenfan.magic.service.IScriptsService;
import com.chenfan.magic.utils.StringKit;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 服务实现类
 *
 * @author troy
 */
@Service
@AllArgsConstructor
public class ScriptsServiceImpl extends ServiceImpl<ScriptsMapper, IdcScripts> implements IScriptsService {

    @Override
    public R get(String scriptIdOrIndexOrRoute) {
        if (StringKit.isBlank(scriptIdOrIndexOrRoute)) {
            return S.fail(S.MQL_CAN_NOT_FOUND);
        }
        //id是纯数字, 路由带/, 索引不带特殊字符
        boolean isIndex = scriptIdOrIndexOrRoute.contains("_");
        boolean isRoute = scriptIdOrIndexOrRoute.contains("/");
        IdcScripts idcScripts = null;
        if (isRoute) {
            //考虑支持restful风格: /rest / user / 1 => /rest / user / {userId}
            idcScripts = this.getOne(Wrappers.<IdcScripts>query().lambda().eq(IdcScripts::getRoute, scriptIdOrIndexOrRoute));
        } else {
            if (isIndex) {
                idcScripts = this.getOne(Wrappers.<IdcScripts>query().lambda().eq(IdcScripts::getIndez, scriptIdOrIndexOrRoute));
            } else {
                idcScripts = this.getById(scriptIdOrIndexOrRoute);
            }
        }
        if (idcScripts == null) {
            return S.fail(S.MQL_NOT_EXIST);
        } else {
            //脚本基础合法性判断
            if (StringKit.isBlank(idcScripts.getContext())) {
                return S.fail(S.MQL_CONTEXT_NULL);
            }
            if (StringKit.isBlank(idcScripts.getMethod())) {
                return S.fail(S.MQL_INVAILD_REST);
            }
            return R.success().put(idcScripts);
        }
    }
}
